package com.zues.rabbit_springboot_producer.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;

/**
 * @ClassName RabbitConfig
 * @Description TODO
 * @Author zeus
 * @Date 6/22/2025 8:50 下午
 * @Version 1.0
 **/
@Configuration
@Slf4j
public class RabbitConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    @Bean
    @Primary
    public RabbitAdmin customRabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }

    /**
     * 消息发送到交换机成功或失败是调用这个方法
     *
     * @param correlationData 消息对象
     * @param ack             是否成功
     * @param cause           失败原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info("confirm() 回调函数打印 CorrelationData: {}", correlationData);
        log.info("confirm() 回调函数打印 ack: {}", ack);
        log.info("confirm() 回调函数打印 cause: {}", cause);
    }

    /**
     * 发送消息失败后才会调用这个方法
     *
     * @param returnedMessage 消息对象
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.info("returnedMessage() 回调函数 消息主体: {}", new String(returnedMessage.getMessage().getBody()));
        log.info("returnedMessage() 回调函数 应答码: {}", returnedMessage.getReplyCode());
        log.info("returnedMessage() 回调函数 描述: {}", returnedMessage.getReplyText());
        log.info("returnedMessage() 回调函数 消息使用的交换机 exchange: {}", returnedMessage.getExchange());
        log.info("returnedMessage() 回调函数 消息使用的路由键 routing: {}", returnedMessage.getRoutingKey());
    }
}
